package com.botao.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.botao.cms.dao.UserMapper;
import com.botao.cms.pojo.User;
import com.botao.cms.service.UserService;
import com.botao.cms.utils.Md5Util;
import com.botao.cms.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public boolean register(String email, String password) {
        Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("email", email));
        if (count == 0) {
            User user = new User();
            user.setId(UUIDUtil.getuuid())
                    .setUsername("桃子")
                    .setCreated(new Date())
                    .setEmail(email)
                    .setPassword(Md5Util.encodeByMd5(password))
                    .setState(1);
            int i = userMapper.insert(user);
            return i != 0;
        } else {
            return false;
        }
    }

    @Override
    public User login(String email, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email));
        if (user == null) {
            return null;
        }
        if (user.getPassword().equals(Md5Util.encodeByMd5(password))) {
            user.setPassword("");
            return user;
        } else {
            return null;
        }
    }

    @Override
    public boolean addUser(User user) {
        Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("email", user.getEmail()));
        if (count == 0) {
            user.setId(UUIDUtil.getuuid()).setPassword(Md5Util.encodeByMd5(user.getPassword())).setCreated(new Date());
            return userMapper.insert(user) != 0;
        } else {
            return false;
        }
    }

    @Override
    @Async
    public void sendEmailToUser(String id, String title, String desc) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("2867970722@qq.com");
        simpleMailMessage.setSubject(title);
        simpleMailMessage.setTo(user.getEmail());
        simpleMailMessage.setText(desc);
        javaMailSender.send(simpleMailMessage);
    }
}
